package com.zrm.zfcrpa.controller.loginController;

import com.zrm.zfcrpa.dao.entity.MyBaseExpiretion;
import com.zrm.zfcrpa.vo.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     */
    @PostMapping("/sendCode")
    public ResultResponse<String> sendCode(@RequestParam String phone){
        String code = String.valueOf((int)((Math.random()*9+1)*1000));
        //设置有效时间，单位秒
        Integer time = 600;
      /*  SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = AliyunSmsUtils.sendSms(phone,code);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if(sendSmsResponse.getCode()!=null && sendSmsResponse.getCode().equals("OK")){
            redisTemplate.opsForValue().set(phone,code,600, TimeUnit.SECONDS);
            logger.info("手机发送验证是验证码是：{}",code);
        }else {
            logger.info("短信发送失败");
        }*/
        //模拟测试
        redisTemplate.opsForValue().set(phone,code,time, TimeUnit.SECONDS);
        logger.info("手机发送验证是验证码是：{}",code);
        return ResultResponse.success("验证码有效时间为："+time+"秒");
    }

    /**
     * 系统内部转发异常处理
     * @param request
     */
    @RequestMapping(value = "/MyExpiretionHandler")
    public void MyExpiretionHandler(HttpServletRequest request){
        throw new MyBaseExpiretion(request.getAttribute("msg").toString(),request.getAttribute("e").toString());
    }

}
